package com.cgc.venus.server.core.k8s.impl;

import com.cgc.venus.server.core.bean.response.VenusResponseStatus;
import com.cgc.venus.server.core.exception.VenusException;
import com.cgc.venus.server.core.k8s.inter.K8sNamespaceService;
import com.cgc.venus.server.core.utils.StringUtil;
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/9/19.
 */
@Service
public class K8sNamespaceServiceImpl implements K8sNamespaceService {
    @Autowired
    private KubernetesClient k8sClient;

    /**
     * 创建命名空间
     * @param name
     * @return
     * @throws VenusException
     */
    @Override
    public boolean createNamespace(String name) throws VenusException {
        if(StringUtil.isEmpty(name)){
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "命名空间不能为空!");
        }
        Namespace tmp=queryNamespace(name);
        if(tmp!=null){
            throw new VenusException(VenusResponseStatus.DATA_REPEAT, "命名空间已经存在!");
        }
        Namespace namespace=new io.fabric8.kubernetes.api.model.Namespace();
        ObjectMeta objectMeta=new ObjectMeta();
        objectMeta.setName(name);
        namespace.setMetadata(objectMeta);
        Namespace namespace1=k8sClient.namespaces().create(namespace);
        if(namespace1==null){
            throw new VenusException(VenusResponseStatus.K8S_EXCEPTION, "创建命名空间失败!");
        }
        return true;
    }

    /**
     * 查询命名空间
     * @param name
     * @return
     * @throws VenusException
     */
    @Override
    public Namespace queryNamespace(String name) throws VenusException {
        Resource<Namespace,DoneableNamespace> resource=k8sClient.namespaces().withName(name);
        Namespace namespace=resource.get();
        return namespace;
    }

    /**
     * 删除命名空间
     * @param name
     * @return
     * @throws VenusException
     */
    @Override
    public boolean deleteNamespace(String name) throws VenusException {
        Namespace namespace=queryNamespace(name);
        return k8sClient.namespaces().delete(namespace);
    }

    /*
    * 创建镜像仓库的秘钥,拉取镜像的时候用
    * */
    @Override
    public boolean createHarborSecret(String harborUrl, String username, String password,String namespace) throws VenusException {
        try {
            StringBuilder sb = new StringBuilder();
            BASE64Encoder encoder = new BASE64Encoder();
            //String a = "{\""+harborUrl+"\":{\"username\":\""+username+"\",\"password\":\""+password+"\",\"email\":\"team@domain.com\",\"auth\":\""++"\"}}";

            Map<String,String> data  = new HashMap<String, String>();

            String auth = username +":" + password;


            sb.append("{\"").append(harborUrl).append("\":{\"username\":\"").append(username);
            sb.append("\",\"password\":\"").append(password);
            sb.append("\",\"email\":\"team@domain.com\",\"auth\":\"").append(encoder.encode(auth.getBytes())).append("\"}}");

            String json  = encoder.encode(sb.toString().getBytes());

            data.put(".dockercfg",json);
            Secret secret = new SecretBuilder()
                    .withNewMetadata()
                    .withName("harbor-default")
                    .withNamespace(namespace)
                    .endMetadata()
                    .withData(data)
                    .withType("kubernetes.io/dockercfg")
                    .build();
            secret = k8sClient.secrets().inNamespace(namespace).create(secret);
            if (secret != null ) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }
}
